package com.itheima.reggie.config;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.math.BigInteger;

@Slf4j
@WebFilter(urlPatterns = "/*",filterName = "loginCheckFilter")
public class LoginFilter implements Filter {

    private static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
         HttpServletRequest request = (HttpServletRequest) servletRequest;
         HttpServletResponse response = (HttpServletResponse) servletResponse;

         String[] urls = {
                 "/employee/login",
                 "/employee/logout",
                 "/backend/**",
                 "/front/**",
                 "/common/**",
                 "/user/sendMsg",
                 "/user/login",
                 "/user/logout",
                 "/user/sendMsg",
                 "/**/plugins/**",
                 "/**/styles/**",
                 "/**/*.ico"
         };
         String uri = request.getRequestURI();
         log.info("过滤到的请求{}",uri);
         boolean check = check(urls, uri);

         if (check) {
            //请求Boolean返回true则直接放行请求
            chain.doFilter(request,response);
            return ;  //防止放行后 资源执行完毕 又接着执行下面的代码 产生冲突
         }

         //如果不是可以直接放行的请求 则判断用户是否登录
        //获取session
        HttpSession session = request.getSession();
        BigInteger empId = (BigInteger) session.getAttribute("employee");
        if (null != empId) {
            //进入到这个方法体说明用户已经登录
            log.info("当前管理端存储的Id:{}",empId);
            BaseContext.setCurrentId(empId.longValue());
            chain.doFilter(request,response);
            return;
        }

        //判断登录状态，如果登录则进行放行
        Object user = request.getSession().getAttribute("user");
        if (user != null) {
            log.info("当前移动端登录用户ID:{}",user);
            Long userId = (Long)user;
            BaseContext.setCurrentId(userId);
            chain.doFilter(request,response);
            return;
        }

        //程序能够执行到这里说明用户没有登录 我们使用servlet相应器回显数据

        response.getWriter().write(JSON.toJSONString(new R<String>(0,"NOTLOGIN",null)));

    }

    /**
     * 路径匹配，检查本次请求是否需要放行
     * @param urls
     * @param requestURI
     * @return
     */
    public boolean check(String[] urls,String requestURI) {
        if (urls == null || 0 == urls.length) return false;

        for (String url : urls) {

            boolean match = PATH_MATCHER.match(url, requestURI);
            if (match) {
                return true;
            }
        }

        return false;
    }

}




